package com.wzdigit.wms.raw.config.druid;
/*
 * @Author:yangwenbiao
 * @Date 2021/5/23 2:41 PM
 * @version 1.0
 */

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 德鲁伊UI配置
 */
@Configuration
public class DruidConfig {

    @Bean
    public ServletRegistrationBean druidServlet() { // 主要实现WEB监控的配置处理
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); // 现在要进行druid监控的配置处理操作

//        servletRegistrationBean.addInitParameter("allow", "127.0.0.1,10.123.111.11"); // 白名单
        // servletRegistrationBean.addInitParameter("deny", "192.168.1.200"); // 黑名单
        servletRegistrationBean.addInitParameter("loginUsername", "druid_admin"); // 用户名
        servletRegistrationBean.addInitParameter("loginPassword", "druid_administrator"); // 密码
        servletRegistrationBean.addInitParameter("resetEnable", "false"); // 是否可以重置数据源
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*"); // 所有请求进行监控处理
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
        return filterRegistrationBean;
    }

//    @Bean
////    @ConfigurationProperties(prefix = "spring.datasource")
////    public DataSource druidDataSource() {
////        return new DruidDataSource();
////    }

    @Bean
    public Filter filter(){
        StatFilter statFilter = new StatFilter();
        // SQL执行时间超过2s种的被判定为慢日志
        statFilter.setSlowSqlMillis(2000);
        //显示慢日志
        statFilter.setLogSlowSql(true);
        //合并SQL，有时，一些相同的慢日志过多影响阅读，开启合并功能
        statFilter.setMergeSql(true);
        return statFilter;
    }


//     ConfigurationProperties可以直接把应用配置的spring.datasource.druid属性开头的值注入到DruidDataSource中
//    @ConfigurationProperties(prefix = "spring.datasource")
//    @Bean(initMethod = "init",destroyMethod = "close")
//    @Primary
//    public DruidDataSource druidDataSource(){
//        DruidDataSource druidDataSource = new DruidDataSource();
//
//        // 添加druid的监控过滤器，当前只演示监控的功能，因此只有一个过滤器，可以实现多个过滤器
//        LinkedList<Filter> filtersList = new LinkedList();
//        filtersList.add(filter());
//        druidDataSource.setProxyFilters(filtersList);
//
//        return druidDataSource;
//    }
}
